package com.demo.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.OSSObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 处理下载的逻辑
 */
@Controller
@RequestMapping("/download")
public class DownloadController {

    @RequestMapping("/jpg")
    public ResponseEntity<byte[]> download(@RequestParam("filename") String filename) throws IOException {
        System.out.println("filename:"+filename);
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = "tianjin-java2";
        //  AccessKey ID   LTAI5tQQYTNT48o5JQtNwmoC
        //  AccessKey Secret mHgiViLkv5pnNnbCCGPaa3jVugOlIB
        String accessKeyId = "LTAI5tQQYTNT48o5JQtNwmoC";
        String accessKeySecret = "mHgiViLkv5pnNnbCCGPaa3jVugOlIB";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量
        DefaultCredentialProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        OSSObject ossObject = ossClient.getObject(bucketName, filename);

        InputStream inputStream = ossObject.getObjectContent();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 读取文件内容到字节数组。
        byte[] readBuffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(readBuffer)) != -1) {
            byteArrayOutputStream.write(readBuffer, 0, bytesRead);
        }
        // 获取最终的字节数组。
        byte[] bytes = byteArrayOutputStream.toByteArray();
        // 在给客户端响应下载内容的时候，需要设置响应头，让浏览器直接下载
        MultiValueMap<String ,String> headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename="+filename);
        // 可以读取本地文件进行下载，也可以获取oss上文件进行下载
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        inputStream.close();
        byteArrayOutputStream.close();
        ossObject.close();
        return responseEntity;
    }

}
